﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Seven.Entity;
using Seven.EntityBasic;
using Seven.DataModel.RepositoryModels.UserAbout;
using Seven.DataModel.ViewModels.UserAbout;
using Seven.Tools.Extension;
using Seven.Web.IntelligentQuery.Extensions;

namespace Seven.MsSql.Repositories
{
    public partial class SysUserRepository
    {
        #region 获取简单模型数据

        public IEnumerable<SimpleModel1> GetSimpleModelByDeptID(int deptId)
        {
            var data = this.Entities().Where(w => w.Staff.DeptID == deptId && !w.IsDeleted).Select(s => new { s.ID, s.Staff.RealName, s.Staff.Sex }).ToArray();

            return data.Select(s => s.CastTo<SimpleModel1>());
        }

        #endregion

        /// <summary>
        /// 根据登录帐号获取用户实体，附带员工实体信息
        /// </summary>
        /// <param name="account">登录帐号，可以是用户名或登录别名</param>
        /// <returns></returns>
        public SysUser GetUserByAccount(string account)
        {
            return this.Entities().Where(w => w.UserName == account || w.LoginCode == account).Include(s => s.Staff).FirstOrDefault();
        }

        /// <summary>
        /// 根据用户ID获取供编辑的数据模型
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        public UserModel GetEditModelByID(int id)
        {
            var user = this.Entities().Where(w => w.ID == id);
            var role = new SysRoleRepository(this.dbContext).Entities();
            var staff = new HrStaffRepository(this.dbContext).Entities();

            var query = (from a in user
                         join b in role on a.RoleID equals b.ID
                         join c in staff on a.StaffID equals c.ID
                         select new
                         {
                             a.ID,
                             a.UserName,
                             a.LoginCode,
                             a.StaffID,
                             a.RoleID,
                             c.CompanyID,
                             c.DeptID,
                             a.Remark,
                             RoleName = b.Name,
                             RealName = c.RealName
                         });

            return query.FirstOrDefault().CastTo<UserModel>();
        }

        /// <summary>
        /// 检查账号（用户名、登录别名）是否存在
        /// </summary>
        /// <param name="account">账号</param>
        /// <param name="id">需要忽略的用户的主键值，默认值为0。新增时判定可不传key参数，更新时判定则key传当前用户的主键</param>
        /// <returns></returns>
        public bool AccountExist(string account, int id)
        {
            return this.Any(a => (a.UserName == account || a.LoginCode == account) && a.ID != id);
        }

        /// <summary>
        /// 判定指定角色ID下是否存在有效用户
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns></returns>
        public bool UseableUserExistByRoleID(int roleId)
        {
            return this.Any(a => a.RoleID == roleId && !a.IsDeleted && !a.IsDisabled);
        }

        /// <summary>
        /// 判定指定员工ID是否存在对应的用户
        /// </summary>
        /// <param name="staffId">员工ID</param>
        /// <returns></returns>
        public bool UseableUserExistByStaffID(int staffId)
        {
            return this.Any(a => a.StaffID == staffId && !a.IsDeleted && !a.IsDisabled);
        }

        /// <summary>
        /// 根据组织结构ID集合，获取他们的下属用户的数量，以Dic形式返回数据，其中Key为ids的元素，Value为其下一级组织结构数量
        /// </summary>
        /// <param name="ids">组织结构ID集合</param>
        /// <param name="type">组织结构类型，该参数决定搜索方式</param>
        /// <returns></returns>
        public IDictionary<int, int> GetUsersCountByOrganIDs(IEnumerable<int> ids, OrganType type)
        {
            var result = new Dictionary<int, int>();
            if (ids.Count() == 0) { return result; }
            if (type == OrganType.子集团)
            {
                var data = this.Entities().Where(w => !w.IsDeleted && !w.IsDisabled && ids.Contains(w.Staff.GroupID)).GroupBy(g => g.Staff.GroupID).Select(s => new { s.Key, Value = s.Count() });
                foreach (var item in data)
                {
                    result.Add(item.Key, item.Value);
                }
            }
            else if (type == OrganType.公司)
            {
                var data = this.Entities().Where(w => !w.IsDeleted && !w.IsDisabled && ids.Contains(w.Staff.CompanyID)).GroupBy(g => g.Staff.CompanyID).Select(s => new { s.Key, Value = s.Count() });
                foreach (var item in data)
                {
                    result.Add(item.Key, item.Value);
                }
            }
            else if (type == OrganType.部门)
            {
                var data = this.Entities().Where(w => !w.IsDeleted && !w.IsDisabled && ids.Contains(w.Staff.DeptID)).GroupBy(g => g.Staff.DeptID).Select(s => new { s.Key, Value = s.Count() });
                foreach (var item in data)
                {
                    result.Add(item.Key, item.Value);
                }
            }

            return result;
        }

        /// <summary>
        /// 获取用户管理列表数据
        /// </summary>
        /// <param name="companyId">公司ID</param>
        /// <param name="deptId">部门ID</param>
        /// <param name="positionId">岗位ID</param>
        /// <param name="roleId">角色ID</param>
        /// <param name="model">序列化的查询条件</param>
        /// <param name="page">页码</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        public IEnumerable<UserGridModel> UserManageGrid(int? companyId, int? deptId, int? positionId, int? roleId, string model, int page, int rows)
        {
            var user = this.Entities().Where(w => !w.IsDeleted);
            var staff = new HrStaffRepository(this.dbContext).Entities();
            var company = new HrOrganizationRepository(this.dbContext).Entities();
            var role = new SysRoleRepository(this.dbContext).Entities();

            var dicModel = new Dictionary<string, string>();
            var queryModel = this.ConvertQueryModel(model, ref dicModel);
            if (queryModel != null) { user = user.Where(queryModel); }
            if (dicModel.Count > 0)
            {
                string param1 = "UserName", value1 = string.Empty;
                if (dicModel.ContainsKey(param1))
                {
                    value1 = dicModel[param1];
                    user = user.Where(w => w.UserName == value1 || w.LoginCode == value1);
                }
            }

            #region 查询条件组织

            if (companyId.HasValue)
            {
                staff = staff.Where(w => w.CompanyID == companyId.Value);
            }
            if (deptId.HasValue)
            {
                staff = staff.Where(w => w.DeptID == deptId.Value);
            }

            #endregion

            var query = (from a in user
                         join b in staff on a.StaffID equals b.ID
                         join c in company on b.CompanyID equals c.ID
                         join d in role on a.RoleID equals d.ID
                         select new
                         {
                             a.ID,
                             a.UserName,
                             a.LoginCode,
                             a.IsDisabled,
                             b.RealName,
                             CompanyName = c.Name,
                             DeptName = b.Dept.Name,
                             RoleName = d.Name
                         });

            var result = query.OrderBy(o => o.ID).SplitPage(page - 1, rows).ToArray();

            return result.Select(s => s.CastTo<UserGridModel>(false));
        }
    }
}
